<template>
    <div class="content">
        <!-- 头部 -->
        <div class="header-setting">
           
            <!-- 面包屑 -->
            <a-breadcrumb class="breadcrumb">
                <a-breadcrumb-item>
                    <a href="../mian">首页</a>
                </a-breadcrumb-item>
                <a-breadcrumb-item>系统配置</a-breadcrumb-item>
                <a-breadcrumb-item>操作人员</a-breadcrumb-item>
            </a-breadcrumb>
            
            <!-- 功能菜单 -->
            <div class="breadcrumb addBtn">
                <template v-if="isSelectRoot || isSelectPath || isSelectLeaf">
                    <!-- 树叶得时候 -->
                    <a-button v-if="isSelectRoot || isSelectPath" :loading="addGroupLoading" type="primary" icon="plus" @click="addPermissionGroup">
                        添加
                    </a-button>
                    <!-- 树叶+根节点得时候 -->
                    <a-button v-if="isSelectPath" type="primary" icon="user-add" @click="showUserPopup">
                        添加操作员岗位
                    </a-button>
                    <template v-if="isSelectPath || isSelectLeaf">
                        <template v-if="!selectedNodeData.children || selectedNodeData.children.length == 0">
                            <a-popconfirm  
                                placement="topLeft"
                                title="确认删除？" okText="确认" cancelText="取消"
                                @confirm="() => {
                                    if(this.isSelectPath) {
                                        this.deletePermissionGroup();
                                    } else if(this.isSelectLeaf) {
                                        this.deleteUser();
                                    }
                                }">
                                <a-button type="danger" icon="delete" :loading="deleteLoading">删除</a-button>
                            </a-popconfirm>
                        </template>
                        <template v-else>
                            <a-button type="danger" icon="delete" 
                                @click="()=> {
                                    this.$message.error('该节点下有数据，请先删除节点下数据后在删除该节点！');
                                }"
                            >删除</a-button>
                        </template>
                    </template>
                </template>
            </div>
        </div>

        <!-- 主内容 -->
        <div class="main">
            
            <!--  左侧栏 -->
            <div class="left-box">
                <template v-if="peopleTree.length > 0">
                    <a-tree showIcon @select="onSelect" :treeData="peopleTree">
                        <a-icon slot="smile-slot" type="user"/>
                        <a-icon slot="folder-slot" type="folder"/>
                    </a-tree>
                </template>
            </div>

            <!--  右侧栏 -->
            <div class="right-box" v-show="isSelectPath || isSelectLeaf">
                <!-- 用户组详情 -->
                <template v-if="isSelectPath">
                    <a-row>
                        <a-col :span="6">操作员级别名称</a-col>
                        <a-col :span="18">
                            <a-input placeholder="岗位名称" v-model="list.description"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">岗位</a-col>
                        <a-col :span="18">
                            <a-tree checkable defaultExpandParent v-model="checkedKeys" :treeData="postTreeData"/>
                        </a-col>
                    </a-row>
                    <a-row type="flex" justify="center">
                        <a-col>
                            <a-button type="primary" icon="save" @click="modifyRoles">保存</a-button>
                        </a-col>
                    </a-row>
                </template>
                <!-- 用户详情 -->
                <template v-if="isSelectLeaf">
                    <a-row>
                        <a-col :span="6">登录名</a-col>
                        <a-col :span="18">
                            <a-input placeholder="登录名" v-model="selectUserInfo.account"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">姓名</a-col>
                        <a-col :span="18">
                            <a-input placeholder="姓名" v-model="selectUserInfo.nickName"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6"></a-col>
                        <a-col :span="18">
                            <a-checkbox @change="onChange">修改密码</a-checkbox>
                        </a-col>
                    </a-row>
                    <a-row v-if="showPassword">
                        <a-col :span="6">密码</a-col>
                        <a-col :span="18">
                            <a-input-password placeholder="密码" @change="passwordChange"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">负责责任区</a-col>
                        <a-col :span="18">
                            <a-tree checkable defaultExpandParent v-model="selectUserInfo.parks"
                                    :treeData="parkTreeData"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">所属管理员：</a-col>
                        <a-col :span="18">
                            <template>
                                <a-select style="margin: 0 50px 0 10px; width: 200px"
                                          placeholder="请选择管理员"
                                          optionFilterProp="children"
                                          @select="selectLeaders"
                                          v-model="selectedLeader"
                                >
                                    <a-select-option v-for="p in leader" :key="p.userId">{{p.userName}}
                                    </a-select-option>
                                </a-select>
                            </template>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">电话</a-col>
                        <a-col :span="18">
                            <a-input placeholder="电话" v-model="selectUserInfo.phoneNum"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">证件号码</a-col>
                        <a-col :span="18">
                            <a-input placeholder="证件号码" v-model="selectUserInfo.idcard"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">地址</a-col>
                        <a-col :span="18">
                            <a-input placeholder="地址" v-model="selectUserInfo.address"/>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">性别</a-col>
                        <a-col :span="18">
                            <a-input-group compact>
                                <a-select 
                                    style="width: 70%" defaultValue="" :options="sexOptions"
                                    v-model="selectUserInfo.gender"></a-select>
                            </a-input-group>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="6">账号状态</a-col>
                        <a-col :span="18">
                            <a-input-group compact>
                                <a-select style="width: 70%" defaultValue="" :options="accountOptions"
                                          v-model="selectUserInfo.status" :disabled="true"></a-select>
                            </a-input-group>
                        </a-col>
                    </a-row>
                    <a-row type="flex" justify="center">
                        <a-col>
                            <a-button type="primary" icon="save" @click="switchAccount">
                                {{selectUserInfo.status==1?'账号禁用':'账号启用'}}
                            </a-button>
                        </a-col>
                        <a-col>
                            <a-button type="primary" icon="save" @click="updateUser">保存</a-button>
                        </a-col>
                    </a-row>
                </template>
            </div>

        </div>

        <!-- 弹窗 -->
        <a-modal 
            title="添加操作员岗位" centered :confirmLoading="addUserPopupData.loading"
            v-model="addUserPopupData.visible"  @ok="commitCreateUser">
            <a-row>
                <a-col :span="6">登录名</a-col>
                <a-col :span="18">
                    <a-input placeholder="登录名" v-model="addUserPopupData.account"/>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="6">姓名</a-col>
                <a-col :span="18">
                    <a-input placeholder="姓名" v-model="addUserPopupData.nickName"/>
                </a-col>
            </a-row>
        </a-modal>
    </div>
</template>

<script>
    /*  API */
    import PerConfig from '../../api/system/ParkApi'
    /* UI */
    import ARow from "ant-design-vue/es/grid/Row";
    import ACol from "ant-design-vue/es/grid/Col";
    import CommonApi from "../../api/CommonApi";

    // const options = [
    //     {value: '1', label: '管理员'},
    //     {value: '2', label: '监管部门'},
    //     {value: '3', label: '管理公司'},
    //     {value: '4', label: '收费公司'},
    //     {value: '5', label: '其他'}
    // ];

    const sexOptions = [
        {value: 0, label: '男'},
        {value: 1, label: '女'},
    ];

    const accountOptions = [
        {value: 0, label: '禁用'},
        {value: 1, label: '启用'},
    ];

    export default {
        name: "PersonConfig",
        
        components: {ACol, ARow},

        data() {
            return {
                /* --------- 管理员列表 --------- */
                leader: [],
                selectedLeader: '',

                /* --------- 人员树 --------- */
                peopleTree: {},
                selectedKeys: [], 
                selectedNodeData: {},   // 选中的节点数据

                /* --------- 岗位树 --------- */
                postTreeData: [],
                checkedKeys: [],
                list: [],

                /* --------- 停车树 --------- */
                parkTreeData: [],

                /* ---------- 性别 ---------- */
                sexOptions,

                /* ---------- 账号 ---------- */
                accountOptions,

                /* ---------- 层级 ---------- */
                showPassword: false,
                selectUserInfo: {},

                //添加内容
                stationNameData: '',
                showNameData: '',
                addNode: {},
                addPermissions: [],

                //密码
                userPwd: '',

                /* ---- 加载 --------- */
                addUserLoading: false,
                addGroupLoading: false,
                deleteLoading: false,

                /* 用户新增弹窗 */
                addUserPopupData: {
                    loading: false,
                    visible: false,
                    account: "",
                    nickName: "",
                },
            }
        },

        mounted() {
            this.$store.dispatch('showHead');
            /* 人员树 */
            this.initPersonList();
            /* 岗位树 */
            this.initPostTreeData();
            /* 停车树 */
            this.initParkTreeData();
            /* 管理员表 */
            this.flushLeaders();
        },

        methods: {

            /* ---------------- 数据初始化 ---------------- */
            initParkTreeData() {
                PerConfig.parkTree()
                    .then((data) => {this.parkTreeData = data.data })
                    .catch(err => { return this.$message.warn(err.data || "网络异常") });
            },

            /*下拉框,初始化刷新管理人员列表*/
            flushLeaders() {
                CommonApi.getLeaderList().then((data) => {
                    this.leader = data.data;
                }).catch(err => {
                    return this.$message.warn(err.data || "管理人员拉取异常")
                });
            },

            /* ---------------- 人员树 ---------------- */
            initPersonList() {
                PerConfig.getPersonList()
                    .then(data => { 
                        let peopleTree = data.data
                        peopleTree[0].title = peopleTree[0].description;
                        peopleTree[0].key= "R:" + peopleTree[0].id;
                        this.convertTree(peopleTree[0].rolesModels);
                        peopleTree[0].children = peopleTree[0].rolesModels;
                        this.peopleTree = peopleTree;
                    })
                    .catch(() => { this.$message.error("获取人员配置失败") })
            },

            convertTree(array) {
                let len = (array || []).length;
                if(len == 0) return ;               
                for(let i = 0; i < len; i++) {
                    let item = array[i];
                    item.key = "P:" + item.id;
                    item.slots = { icon: 'folder-slot' };
                    item.title = item.description;
                    /* 继续遍历生成路径 */
                    this.convertTree(item.rolesModels)
                    /* 生成枝叶 */
                    let l = (item.userEntities || []).length;
                    for(let j = 0; j < l; j++) {
                        let ei = item.userEntities[j];
                        ei.title = ei.nickName;
                        ei.key = 'L:' + ei.id;
                        ei.slots = { icon: 'smile-slot' };
                        ei.isLeaf = true;
                    }
                    let models = item.rolesModels || [];
                    let entity =  item.userEntities || [];
                    item.children = [...models, ...entity];
                }
            },

            onSelect(selectedKeys, node) {
                this.selectedKeys = selectedKeys;
                this.selectedNodeData = node.node.dataRef;

                if (this.isSelectLeaf) {
                    this.userInfo();

                } else if(this.isSelectPath) {
                    this.getPersonStationList();
                } 
            },

            clearSelect() {
                this.selectedKeys = [];
                this.selectedNodeData = '';
            },
            
            /* ---------------- 岗位树 ---------------- */
            initPostTreeData() {
                PerConfig.getStation()
                    .then(data => {
                        let children = data.data;
                        this.postTreeData = [{ title: '岗位列表', key: 0, children: children }];
                    })
                    .catch(err => {
                        let data = err.data;
                        return this.$message.error(data || '初始化岗位树异常！');
                    });
            },

            modifyRoles() {
                let condition = {};
                condition.id = this.list.id;
                condition.description = this.list.description;
                condition.postTypeId = this.list.postTypeId;
                condition.pid = this.list.pid;
                condition.posts = this.checkedKeys;
                PerConfig.updateRole(condition)
                    .then(data => {
                        this.$message.success('修改成功！');
                        this.initPersonList();
                    })
                    .catch(err => {
                        let data = err.data;
                        if (data) {
                            return this.$message.warn(data);
                        }
                        console.log("网络异常！");
                    });
            },

            getPersonStationList() {
                let { id } = this.selectedNodeData;
                PerConfig.getPersonStationList(id)
                    .then((data) => {
                        this.list = data.data;
                        let posts = data.data.posts;
                        this.checkedKeys = posts == '' ? [] : posts;
                    })
                    .catch(error => {
                        console.log(error)
                    })
            },

            /* --------------------- 权限组 --------------------- */
            addPermissionGroup() {
                let { id } = this.selectedNodeData;
                this.addGroupLoading = true;
                PerConfig.addPersonPost({ pid: id })
                    .then(() => {
                        this.$message.success("添加成功");
                        this.initPersonList();
                        this.addGroupLoading = false;
                    })
                    .catch(() => {
                        this.$message.warn('添加失败');
                        this.addGroupLoading = false;
                    });
            }, 

            deletePermissionGroup() {
                let { id } = this.selectedNodeData;
                this.deleteLoading = true;
                PerConfig.deleteRole(id)
                    .then(() => {
                        this.deleteLoading = false;
                        this.initPersonList();
                        this.clearSelect();
                    })
                    .catch(err => {
                        this.deleteLoading = false;
                        let data = err.data;
                        this.$message.warn(data || '删除角色异常！');
                    });
            },

            /* --------------------- 角色 --------------------- */
            updateUser() {
                let condition = {};
                let selectUserInfo = this.selectUserInfo;
                /* 责任区选择 */
                let parks = selectUserInfo.parks;
                let filterParks = parks.filter(x => {
                    if (isNaN(x)) {
                        return false;
                    }
                    return true;
                });

                condition.id = selectUserInfo.id;
                condition.account = selectUserInfo.account;
                condition.nickName = selectUserInfo.nickName;

                condition.isUpdatePwd = this.showPassword;
                condition.password = this.userPwd;
                condition.gender = selectUserInfo.gender;
                condition.phoneNum = selectUserInfo.phoneNum;
                condition.idcard = selectUserInfo.idcard;
                condition.address = selectUserInfo.address;
                condition.parkIds = filterParks;

                condition.pUserId = (this.selectedLeader == '' || isNaN(this.selectedLeader)) ? 0
                    : parseInt(this.selectedLeader);
                PerConfig.updateUser(condition)
                    .then(() => {
                        this.$message.success('操作成功！');
                    })
                    .catch(err => {
                        let data = err.data;
                        return this.$message.error(data || '更新失败');
                    });
            },

            deleteUser() {
                let { id } = this.selectedNodeData;
                this.deleteLoading = true;
                PerConfig.delUser(id)
                    .then(() => {
                        this.$message.success('操作成功！');
                        this.initPersonList();
                        this.deleteLoading = false;
                        this.clearSelect();
                    })
                    .catch(err => {
                        this.deleteLoading = false;
                        let data = err.data;
                        this.$message.warn(data);
                    });
            },

            // 用户账号禁用 / 启用
            switchAccount() {
                let condition = {
                    id: this.selectUserInfo.id,
                    status: this.selectUserInfo.status === 1 ? 0 : 1
                };
                PerConfig.switchUserAccount(condition)
                    .then(() => {
                        this.$message.success('操作成功！');
                        this.selectUserInfo.status = condition.status;
                    })
                    .catch(err => {
                        let data = err.data;
                        this.$message.warn(data || '网络异常！');
                    });
            },
            
            /* -------------------- 用户处理 -------------------- */          
            userInfo() {
                let { id } = this.selectedNodeData;
                PerConfig.userInfo(id)
                    .then(data => {
                        this.selectUserInfo = data.data;
                        this.selectedLeader = (this.selectUserInfo.pUserId == '' || isNaN(this.selectUserInfo.pUserId)
                            || this.selectUserInfo.pUserId == 0) ? [] : parseInt(this.selectUserInfo.pUserId);
                    })
                    .catch(() => {
                        return this.$message.warn("获取用户信息失败");
                    });
            },

            //密码多选框
            onChange(e) {
                this.showPassword = e.target.checked;
            },

            passwordChange(e) {
                this.userPwd = this.$md5(e.currentTarget.value);
            },

            /* ------------------ 添加用户弹窗 --------------------- */
            showUserPopup() {
                this.addUserPopupData.visible = true;
                this.addUserPopupData.addUserLoading = false;
                this.addUserPopupData.account = "";
                this.addUserPopupData.nickName = "";
            },

            hideUserPopup() {
                this.addUserPopupData.visible = false;
            },

            commitCreateUser() {
                let { account, nickName } = this.addUserPopupData;
                
                account = (account || '').trim();
                if(!account) {
                    this.$message.error("登录名不能为空");
                    return ;
                }

                if( account.length > 11 ) {
                    this.$message.error("登录名长度不能超过11位");
                    return ;
                }

                nickName = (nickName || '').trim();
                if(!nickName) {
                    this.$message.error("姓名不能为空");
                    return ;
                }

                if( nickName.length > 15 ) {
                    this.$message.error("姓名长度不能超过15位");
                    return ;
                }
                
                this.addUserPopupData.loading = true;

                let { id } = this.selectedNodeData;
                let condition = { account, nickName, roleId: id };
                PerConfig.addUser(condition)
                    .then(() => {
                        this.$message.success('操作成功！');
                        this.initPersonList();
                        this.addUserPopupData.addUserLoading = false;
                        this.addUserPopupData.loading = false;
                        this.hideUserPopup();
                    })
                    .catch(err => {
                        this.addUserPopupData.addUserLoading = false;
                        let data = err.data;
                        this.$message.warn(data || '网络异常！');
                    });
            },

        },

        computed: {
            isSelectRoot() {
                let key = this.selectedKeys[0]
                if(!key) return ;
                let c = key.split(':')[0];
                return c === 'R';
            },

            isSelectLeaf() {
                let key = this.selectedKeys[0]
                if(!key) return ;
                let c = key.split(':')[0];
                return c === 'L';
            },

            isSelectPath() {
               let key = this.selectedKeys[0]
                if(!key) return ;
                let c = key.split(':')[0];
                return c === 'P';
            },
        },
    }
</script>

<style scoped>
    input {
        width: 70%;
    }

    .ant-input-affix-wrapper {
        width: 70%;
    }

    /*头部*/
    .content {
        width: 100%;
        height: 100%;
    }

    .header-setting {
        width: 100%;
        height: 124px;
        background: #fff;
        display: flex;
        justify-content: space-between;
        position: relative;
    }

    .header-setting .breadcrumb {
        padding-top: 15px;
        width: 336px;
        margin: 0 40px;
        padding-top: 15px;
    }

    .header-setting .breadcrumb button {
        margin: 0 7px;
    }

    .header-setting .addBtn {
        position: absolute;
        right: 40px;
        bottom: 30px;
        margin: 0;
        padding: 0;
    }

    /*main*/
    .main {
        display: flex;
        background: #fff;
        border-top: 1px solid #ddd;
        /* fixed */
        position: absolute;
        top: 124px;
        bottom: 0;
        left: 0;
        right: 0;
    }

    .main div {
        height: auto;
    }

    .main .left-box {
        width: 20%;
        border-right: 1px solid #ddd;
        padding: 13px 20px 20px;
    }

    .main .right-box {
        flex: 1;
        padding: 20px;
    }

    .ant-row {
        padding: 7px 0;
    }

    .saveDelete button {
        margin: 0 15px
    }

    .ant-row-flex-center button {
        margin: 10px;
    }
</style>
